package com.ohuang.router_compiler.util;




import com.ohuang.router_compiler.RouterInterface;

import java.util.HashMap;

public class RouterUtil {
    private static  volatile RouterUtil routerUtil;
    private HashMap<String, RouterInterface> map;
    public static final  String PATH="com.ohuang.router.RouterMap$";


    private RouterUtil() {
        map=new HashMap<>();
    }

    public static RouterUtil getInstance(){
        if (routerUtil==null){
            synchronized (RouterUtil.class){
                if (routerUtil==null){
                    routerUtil=new RouterUtil();
                }
            }
        }
        return routerUtil;
    }

    public synchronized Class<?> getClassForPath(String path) {
        String key = path.split("/")[0];
        if (!map.containsKey(key)) {
            String s = PATH+key;
            if (TextUtils.isEmpty(key)) {
                throw new RuntimeException("OhRouter not find path" + s);
            }
            try {
                Class<?> clzz = Class.forName(s);
                RouterInterface routeMap = (RouterInterface) clzz.newInstance();
                routeMap.init();
                map.put(key, routeMap);
            } catch (Exception c) {
                throw new RuntimeException("OhRouter can not create class" + s);
            }
        }
        RouterInterface routeMap=map.get(key);
        return routeMap.get(path);
    }

    public Object getObjetForPath(String path){
        Class<?> c=getClassForPath(path);
        Object o;
        try {
            o=c.newInstance();
        }  catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("can not create "+c.getName()+" Path"+path);
        }
        return o;
    }






    public boolean containsKey(String key){
        return map.containsKey(key);
    }

    public void put(String key,RouterInterface routerInterface){
        map.put(key, routerInterface);
    }

}
